package org.fhm.zdte.common.service.message;

import org.fhm.substrate.annotation.BeanEnable;
import org.fhm.substrate.annotation.Component;
import org.fhm.substrate.annotation.Setup;
import org.fhm.substrate.manager.Bootstrap;
import org.fhm.zdte.common.constant.DataTransform;
import org.fhm.zdte.common.constant.protocol.ContentType;
import org.fhm.zdte.common.exception.ProtocolException;
import org.fhm.zdte.common.pojo.Request;
import org.fhm.zdte.common.pojo.ZDTEFile;
import org.fhm.zdte.common.standard.IJsonConvertor;
import org.fhm.zdte.common.util.CommonUtil;

import java.util.Map;
import java.util.Objects;

/**
 * FILE receive message manager.
 *
 * @author 谭波
 * @since 2024/4/3
 */
@Component("FILE")
public class FileReceiveMessageManager extends AbstractReceiveMessageManager {

    @Setup
    private IJsonConvertor iJsonConvertor;

    @Setup
    private CommonUtil commonUtil;

    public FileReceiveMessageManager() {
        super(ContentType.FILE);
    }

    @Override
    public Request convert(byte[] buffer) {
        String content = new String(buffer, Bootstrap.charset);
        String[] split = content.split(DataTransform.PROXY_PACKET_SEPARATOR);
        if (split.length != 2)
            throw new ProtocolException("the accepted file data format is incorrect");
        Request request = iJsonConvertor.fromJson(split[0], Request.class);
        Map<String, Object> params = request.getParams();
        params.put(
                DataTransform.FILE_KEY,
                new ZDTEFile(
                        checkAndGet(
                                params.get(DataTransform.FILE_NAME_KEY)
                        ), split[1]
                )
        );
        return request;
    }

    private String checkAndGet(Object obj) {
        String str;
        if (Objects.isNull(obj) || (str = obj.toString()).isEmpty())
            throw new ProtocolException("the uploaded data is error");
        return str;
    }

    @BeanEnable
    private void beanEnable() {
        setLengthOfPacketWithContent();
    }

}
